/**
 * Từ MainActivity chuyển sang
 */
package com.hao.main;

import java.util.ArrayList;

import GiaoHangVietNam.Entities.InterChangeInvoices;
import GiaoHangVietNam.Entities.InvoiceDetails;
import GiaoHangVietNam.RawInfor.EventCode;
import GiaoHangVietNam.RawInfor.GlobalStatus;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class InterChangInvoiceDetailActivity extends Activity implements
		OnClickListener,Runnable {

	Button confirmShipInterChangeBtn, confirmNotShipInterChangeBtn;

	TextView nameCustomerInterChangeTv, phoneNumberInterChangeTv,
			addressCusInterChangeTv;
	LinearLayout callReceiverInterChangeLnl, googleMapInterChangeLnl;

	ListView listSendInterChangeLv, listReceiveInterChangeLv;
	InterChangeInvoidAdapter sendAdapter, receiverAdapter;

	InterChangeInvoices InterChange;

	ProgressDialog showDialog;
	boolean flag=false;
	/** đánh dấu trạng thái đơn hàng (hủy hay xác nhận) */
	boolean isFinish = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inter_change_invoices);

		confirmNotShipInterChangeBtn = (Button) findViewById(R.id.confirm_not_ship_inter_change_btn);
		confirmNotShipInterChangeBtn.setOnClickListener(this);
		confirmShipInterChangeBtn = (Button) findViewById(R.id.confirm_ship_inter_change_btn);
		confirmShipInterChangeBtn.setOnClickListener(this);
		nameCustomerInterChangeTv = (TextView) findViewById(R.id.name_customer_inter_change_tv);
		phoneNumberInterChangeTv = (TextView) findViewById(R.id.phone_number_shipper_inter_change_tv);
		addressCusInterChangeTv = (TextView) findViewById(R.id.address_interchange_tv);
		callReceiverInterChangeLnl = (LinearLayout) findViewById(R.id.call_receiver_inter_change_lnl);
		callReceiverInterChangeLnl.setOnClickListener(this);
		googleMapInterChangeLnl = (LinearLayout) findViewById(R.id.google_map_inter_change_lnl);
		googleMapInterChangeLnl.setOnClickListener(this);

		listSendInterChangeLv = (ListView) findViewById(R.id.shiper_send_lv);
		listReceiveInterChangeLv = (ListView) findViewById(R.id.shiper_receiver_lv);

		getPara();
	}
	private void playMusicFile()
	{
		// Rung chuông, file nhạc đặt trong thư mục raw trong res, có thể chơi mọi đuôi nhạc, mp3,mp4...
		 MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.alarm);
	        mPlayer.start();
	}
	// Lấy dữ liệu từ intent gửi từ main Activity sang, set vào các controls
	// dang set du lieu gia
	public void getPara() {
		// Chia 2 loại bản tin

		// lấy intent gọi Activity này
		Intent callerIntent = getIntent();
		// Thông tin cần chuyển đổi đơn hàng
		InterChange = (InterChangeInvoices) callerIntent
				.getSerializableExtra("MyPackage");

		// Add dữ liệu vào 2 listView
		sendAdapter = new InterChangeInvoidAdapter(
				InterChangInvoiceDetailActivity.this,
				R.layout.detail_invoice_list_inter_change_item,
				InterChange.ListInvoiceSend);
		listSendInterChangeLv.setAdapter(sendAdapter);

		receiverAdapter = new InterChangeInvoidAdapter(
				InterChangInvoiceDetailActivity.this,
				R.layout.detail_invoice_list_inter_change_item,
				InterChange.ListInvoiceReceive);

		listReceiveInterChangeLv.setAdapter(receiverAdapter);

		phoneNumberInterChangeTv.setText(InterChange.Number);
		nameCustomerInterChangeTv.setText(InterChange.OtherName);
		addressCusInterChangeTv.setText(InterChange.Address);

	 
		// TODO Auto-generated method stub
		android.app.AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Yêu cầu chuyển giao hàng");
		alert.setMessage("Hãy gọi điện cho shipper " + InterChange.OtherName);
		alert.setPositiveButton("OK", null);
		alert.show();
		Vibrator v = (Vibrator) this
				.getSystemService(Context.VIBRATOR_SERVICE);
		v.vibrate(500); 
		playMusicFile();
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.confirm_ship_inter_change_btn: 
					FinishInvoiceInterChange();   
			break;
		case R.id.confirm_not_ship_inter_change_btn: 
					CancelInvoiceInterChange();  
			break;
		case R.id.call_receiver_inter_change_lnl:
			callShipper();
			break;
		case R.id.google_map_inter_change_lnl:
			startGoogleMap();
			break;
		default:
			break;
		}

	}

	// Xử lý phím back mặc định trên android
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			onBackPressed();

		}
		return false;
	}

	@Override
	public void onBackPressed() {
		// super.onBackPressed();

		showDialog("Hãy xác nhận việc chuyển giao hàng");
	}

	// gọi tới người nhận
	public void callShipper() {

		String uri = "tel:" + phoneNumberInterChangeTv.getText() + "".trim();
		Intent intent = new Intent(Intent.ACTION_CALL);
		intent.setData(Uri.parse(uri));
		this.startActivity(intent);
	}

	// Chuyển sang map
	public void startGoogleMap() {
		// sang Activity về GoogleMap có Bundle dữ liệu là tọa độ điểm cần
		Intent intent = new Intent(this, GoogleMapActivity.class);
		intent.putExtra("Lat", InterChange.Lat);
		intent.putExtra("Lng", InterChange.Lng);
		intent.putExtra("Number", InterChange.Number);
		intent.putExtra("CustomerName", InterChange.OtherName);
		intent.putExtra("CompanyName", "Điểm trung chuyển");
		intent.putExtra("IsSending", true);
		intent.putExtra("ListGoodsName", "");
		startActivity(intent);
	}

	private void FinishInvoiceInterChange() {
		AlertDialog.Builder b = new AlertDialog.Builder(
				InterChangInvoiceDetailActivity.this);

		b.setTitle("Xác nhận chắc chắn!");
		b.setMessage("Đã chuyển giao hàng");
		b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				
				isFinish = true;
				showDialog = ProgressDialog.show(InterChangInvoiceDetailActivity.this,
						"Kết nối..", "Đang chờ", true, false);
				Thread thread = new Thread(InterChangInvoiceDetailActivity.this);
				thread.start();
			}
		});
		b.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which)

			{
				dialog.cancel();
			}
		});
		b.create().show();

	}

	private void CancelInvoiceInterChange() {
		AlertDialog.Builder b = new AlertDialog.Builder(
				InterChangInvoiceDetailActivity.this);

		b.setTitle("Xác nhận chắc chắn!");
		b.setMessage("Hủy chuyển giao");
		b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				isFinish = false;
				showDialog = ProgressDialog.show(InterChangInvoiceDetailActivity.this,
						"Kết nối..", "Đang chờ", true, false);
				Thread thread = new Thread(InterChangInvoiceDetailActivity.this);
				thread.start();
			}
		});
		b.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which)

			{
				dialog.cancel();
			}
		});
		b.create().show();

	}

	// Hàm gửi dữ liệu về Activity1
	public void sendToMain(int value, int resultcode) {
		Intent intent = getIntent();
		Bundle bundle = new Bundle();
		bundle.putInt("InvoiceStatus", value);
		intent.putExtra("MyPackage", bundle);
		setResult(resultcode, intent); // phương thức này sẽ trả kết quả cho
										// Activity1
		finish(); // Đóng Activity hiện tại
	}

	// kiểm tra kết nối internet
	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	// hiển thị diaglog thông báo chưa kết nối internet;
	private void showDialog(String content) {
		AlertDialog.Builder b = new AlertDialog.Builder(
				InterChangInvoiceDetailActivity.this);

		b.setTitle("Thông báo! ");
		b.setMessage(content);
		b.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		b.create().show();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		staskBackground stask = new staskBackground();

		flag = stask.countNumber();
		handler.sendEmptyMessage(0);
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			showDialog.dismiss();
			if (flag) {
				if (isFinish) {
					sendToMain(EventCode.FINISH_INTERCHANGE,
							MainActivity.INVOICE_STATUS);
				} else {
					sendToMain(EventCode.CANCEL_INTERCHANGE,
							MainActivity.INVOICE_STATUS);
				}

			} else {
				Toast.makeText(getApplicationContext(), "Chưa kết nối Internet! ", Toast.LENGTH_LONG).show();
			}
		}
	};
}
